package com.jeect.productservice.service;

import com.jeect.base.domain.Product;
import com.jeect.base.util.RedisCacheKey;
import com.jeect.productservice.event.RedisEvent;
import com.jeect.productservice.mapper.ProductMapper;
import com.jeect.productservice.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ApplicationContext context;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    @Transactional
    public void saveProduct(Product product) {
        if(product!=null && !StringUtils.isEmpty((product.getSku()))) {
            productMapper.save(product);
            /*Map<String, Object> map = new HashMap<>();
            map.put(product.getSku(),product);*/
            /**
             * 替换为事件驱动 解耦
             */
//            RedisUtil redisUtil = new RedisUtil(redisTemplate);
//            redisUtil.hmset("products", map);

            /**
             * 解耦后替换为
             */
            RedisEvent event = new RedisEvent(this,createEventTarget(product));
            context.publishEvent(event);

        }

    }

    @Override
    public Product getBySku(String sku) {
        RedisUtil redisUtil = new RedisUtil(redisTemplate);
        Product product = (Product)redisUtil.hget("products",sku);
        if(product==null){
            System.out.println("product is null!!!");
            product =  productMapper.getBySku(sku);
            /**
             * 事件驱动  异步处理 提高性能
             */
            RedisEvent event = new RedisEvent(this,createEventTarget(product));
            context.publishEvent(event);
        }else{
            System.out.println("product is not null!!!");
        }
        return product;
    }

    @Override
    public Boolean updateProduct(Product product) {
        if(!StringUtils.isEmpty(product.getSku())){
            productMapper.updateProduct(product);

            Product p = this.productMapper.getBySku(product.getSku());
            RedisEvent event = new RedisEvent(this,createEventTarget(p));
            context.publishEvent(event);
            return true;
        }
        return false;
    }

    private Map<String,Map<String,Object>> createEventTarget(Product product){
        Map<String, Map<String, Object>> target = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put(product.getSku(),product);
        target.put(RedisCacheKey.PRODUCT,map);
        return target;
    }
}
